﻿using System;
using System.IO;
using System.Linq;
using VirtualDeveloper;
using Xunit;

namespace UnitTest
{
    public class TempDirectoryWithContent : IDisposable
    {
        private readonly string tempDirectory;

        public TempDirectoryWithContent()
        {
            tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            var subfolder = Path.Combine(DirectoryPath, "subfolder");

            Directory.CreateDirectory(DirectoryPath);
            Directory.CreateDirectory(subfolder);

            CreateTextFile(Path.Combine(DirectoryPath, "toto.txt"));
            CreateTextFile(Path.Combine(subfolder, "titi.txt"));
        }

        public string DirectoryPath
        {
            get { return tempDirectory; }
        }

        private static void CreateTextFile(string filePath)
        {
            using (var stream = File.Open(filePath, FileMode.Create, FileAccess.Write))
            using (var writer = new StreamWriter(stream))
            {
                writer.Write("hello");
            }
        }

        public void Dispose()
        {
            Directory.Delete(DirectoryPath, true);
        }
    }

    public class TempTestFile : IDisposable
    {
        private readonly string filePath;
        private readonly Stream fileStream;

        public TempTestFile()
        {
            filePath = Path.GetTempFileName();

            using (fileStream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
            {

            }
        }

        public string FilePath
        {
            get { return filePath; }
        }

        public void Dispose()
        {
            fileStream.Dispose();
            File.Delete(filePath);
        }
    }

    public class FileAdapterTest
    {
        private readonly IFileAdapter fileAdapter = new FileAdapter();

        [Fact]
        public void get_files()
        {
            using (var tempDirectoryWithContent = new TempDirectoryWithContent())
            {
                var files = fileAdapter.GetFiles(tempDirectoryWithContent.DirectoryPath, "*.txt");

                Assert.Equal(2, files.Count());
            }
        }

        [Fact]
        public void write_toto_to_hello_file()
        {
            using (var file = new TempTestFile())
            {
                fileAdapter.SaveToFile(file.FilePath, "hello");
                Assert.Equal("hello", fileAdapter.ReadAllText(file.FilePath));
            }
        }
    }
}
